package com.github.defense.plugin.gray.context;


import com.github.defense.plugin.gray.interceptor.GrayInterceptor;
import com.github.defense.plugin.gray.manager.GrayManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 所有请求在经过(Zuul,Gateway,RestTemplate,Feign)路由之前先在上下文中存一下数据
 *
 * @Author: lettger
 * @Date: 2021/6/7 1:39 下午
 */
@Slf4j
public class DefaultRoutingHandler implements RoutingHandler {

    private GrayManager manager;
    private GrayLocalContext localContext;

    public DefaultRoutingHandler(GrayManager manager, GrayLocalContext localContext) {
        this.manager = manager;
        this.localContext = localContext;
    }

    @Override
    public void execute(RoutingLocalContext context) {
        RoutingLocalContext.setContextLocal(context);
        localContext.setGrayRequest(context.getRequest());
        List<GrayInterceptor> interceptors = manager.getGrayInterceptor(context.getGrayType());
        if (!CollectionUtils.isEmpty(interceptors)) {
            interceptors.forEach(interceptor -> {
                if (interceptor.isShould() && !interceptor.preHandler(context.getRequest())) {
                    return;
                }
            });
        }
    }

    @Override
    public void destroy(RoutingLocalContext context) {
        log.debug("======== local context  destroy:{}", context.getGrayType().name());
        List<GrayInterceptor> interceptors = manager.getGrayInterceptor(context.getGrayType());
        if (!CollectionUtils.isEmpty(interceptors)) {
            interceptors.forEach(interceptor -> {
                if (interceptor.isShould() && !interceptor.afterHandler(context.getRequest())) {
                    return;
                }
            });
        }
        RoutingLocalContext.removeLocalContext();
        localContext.removeLocalContext();
    }
}
